package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	@Autowired
	private CustomerRepository customerRepository;
	//查询未关联定区的客户
	@Override
	public List<Customer> findNoAssociationCustomers() {
		return customerRepository.findByFixedAreaIdIsNull();
	}
	//查询已关联定区的客户
	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}
	//关联客户到定区，并且解除已关联的客户
	@Override
	public void associationCustomerToFixedArea(String customerIdStr, String fixedAreaId) {
		
		if(StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)){
			//解除关联
			customerRepository.clearAssociationCustomers(fixedAreaId);
			return;
		}else{
			String[] customerIds = customerIdStr.split("-");
			for (String customerId : customerIds) {
				Integer id = Integer.parseInt(customerId);
				customerRepository.updateFixedAreaId(fixedAreaId,id);
			}
		}
	}
	@Override
	public void registCustomer(Customer customer) {
		customerRepository.save(customer);
	}
	
	@Override
	public Customer findCustomerByTelephone(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}
	
	@Override
	public void updateCustomerType(String telephone) {
		customerRepository.updateCustomerType(telephone);
	}
	@Override
	public Customer login(String telephone, String password) {
		
		return customerRepository.findByTelephoneAndPassword(telephone,password);
	}
	@Override
	public String findFixedAreaIdByAddress(String address) {
		return customerRepository.findFixedAreaIdByAddress(address);
	}
}
